package com.vs.meepet.helper

import android.content.Context
import com.geetest.sdk.GT3ConfigBean
import com.geetest.sdk.GT3ErrorBean
import com.geetest.sdk.GT3GeetestUtils
import com.geetest.sdk.GT3Listener
import com.vs.meepet.bean.GeeTestRegisterDataBean
import com.vs.meepet.bean.GeeTestResultBean
import com.vs.meepet.network.GsonUtil
import com.vs.meepet.network.api.userApi
import com.vs.meepet.network.ext.asFlow
import com.vs.meepet.network.ext.toRequestBody
import com.vs.meepet.utils.LogUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 *
 * 作者：柯嘉少
 * 邮箱：2449926649@qq.com
 * 日期: 2024/9/18
 * 修改人: xxx(des)
 * 说明:
 * 版本: 1.0
 */
class GeeTestHelper {
    private var gT3GeeTestUtils: GT3GeetestUtils? = null
    private var configBean: GT3ConfigBean? = null
    private var coroutineScope: CoroutineScope? = null


    fun show(context: Context?, phone: String, dataBean: GeeTestRegisterDataBean?,callBack: (isSuccess: Boolean, msg: String?) -> Unit) {
        if (gT3GeeTestUtils == null && context != null) {
            gT3GeeTestUtils = GT3GeetestUtils(context)
        }
        LogUtils.i("调起人机验证")
        configBean = GT3ConfigBean()
        configBean?.apply {
            pattern = 1
            isCanceledOnTouchOutside = false
            timeout = 10000
        }
        configBean?.listener = object : GT3Listener() {
            /**
             * 验证码加载完成
             * @param duration 加载时间和版本等信息，为json格式
             */
            override fun onDialogReady(duration: String) {
                LogUtils.e("geetest-onDialogReady: $duration")
            }

            /**
             * 图形验证结果回调
             * @param code 1为正常 0为失败
             */
            override fun onReceiveCaptchaCode(code: Int) {
                LogUtils.e("geetest-onReceiveCaptchaCode: $code")
            }

            /**
             * 自定义api2回调
             * @param result，api2请求上传参数
             */
            override fun onDialogResult(result: String) {
                LogUtils.e("geetest-onDialogResult: $result")
                val geeTestResultBean: GeeTestResultBean =
                    GsonUtil.gson.fromJson<GeeTestResultBean>(result, GeeTestResultBean::class.java)
                LogUtils.i("去求获取验证码")

                geeTestResultBean.requestId=dataBean?.requestId

                getPhoneCode(phone, geeTestResultBean) { isSuccess, msg ->
                    if (isSuccess) {
                        gT3GeeTestUtils?.showSuccessDialog()
                    } else {
                        gT3GeeTestUtils?.showFailedDialog()
                    }
                }
            }

            /**
             * 统计信息，参考接入文档
             * @param result
             */
            override fun onStatistics(result: String) {
            }

            /**
             * 验证码被关闭
             * @param num 1 点击验证码的关闭按钮来关闭验证码, 2 点击屏幕关闭验证码, 3 点击返回键关闭验证码
             */
            override fun onClosed(num: Int) {
                LogUtils.e("geetest-onClosed: $num")
            }

            /**
             * 验证成功回调
             * @param result
             */
            override fun onSuccess(result: String) {
                LogUtils.e("geetest-onSuccess: $result")
                if (coroutineScope?.isActive==true){
                    callBack.invoke(true,"")
                }
            }

            /**
             * 验证失败回调
             * @param errorBean 版本号，错误码，错误描述等信息
             */
            override fun onFailed(errorBean: GT3ErrorBean) {
                LogUtils.e("geetest-onFailed: ${GsonUtil.gson.toJson(errorBean)}")
                if (coroutineScope?.isActive==true) {
                    callBack.invoke(false, errorBean.errorDesc)
                }
            }

            /**
             * 自定义api1回调
             */
            override fun onButtonClick() {
                LogUtils.e("geetest-onButtonClick: ${GsonUtil.gson.toJson(dataBean)}")
                configBean?.api1Json = JSONObject(GsonUtil.gson.toJson(dataBean))
                gT3GeeTestUtils?.getGeetest()
            }
        }
        gT3GeeTestUtils?.init(configBean)
        gT3GeeTestUtils?.startCustomFlow()
    }

    private fun getPhoneCode(
        phone: String,
        geeTestResultBean: GeeTestResultBean,
        callBack: (isSuccess: Boolean, msg: String?) -> Unit
    ) {
        if (coroutineScope == null) {
            coroutineScope = CoroutineScope(Job() + Dispatchers.IO)
        }
        userApi.sendCaptcha(
            HashMap<String, Any>().apply {
                put("phone", phone)
                put("requestId", geeTestResultBean.requestId)
                put("gtSeccode", geeTestResultBean.gtSeccode)
                put("gtChallenge", geeTestResultBean.gtChallenge)
                put("gtValidate", geeTestResultBean.gtValidate)
                put("captchaCode", geeTestResultBean.captchaCode ?: "")
            }.toRequestBody()
        ).asFlow().map {
            if (it.isSuccess() && it.data == true) {
                coroutineScope?.launch(Dispatchers.Main) {
                    callBack.invoke(true, "")
                }
            } else {
                coroutineScope?.launch(Dispatchers.Main) {
                    callBack.invoke(false, it.msg ?: "数据请求异常，请重试！")
                }
            }
        }.catch {
            coroutineScope?.launch(Dispatchers.Main) {
                callBack.invoke(false, it.message ?: "数据请求异常，请重试！")
            }
        }.flowOn(Dispatchers.IO).launchIn(coroutineScope!!)
    }

    fun destroy() {
        gT3GeeTestUtils?.dismissGeetestDialog()
        gT3GeeTestUtils?.destory()
        coroutineScope?.cancel()
        coroutineScope = null
    }

}